//
//  KRReadPostController.m
//  cookBook
//
//  Created by kuroken on 16/1/15.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRReadPostController.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import <SVProgressHUD.h>
#import <PureLayout.h>
#import <UITableView+FDTemplateLayoutCell.h>
#import <NJKWebViewProgressView.h>
#import "KRConst.h"
#import "KRReadPost.h"
#import "KRReadComment.h"
#import "KRHttpRecipeTool.h"
#import "KRReadTitleCell.h"
#import "KRPostInfoCell.h"
#import "KRWebViewCell.h"
#import "KRCommentCell.h"
#import "KRReadComment.h"
#import "KRNoNetCell.h"
#import "KRRecipeInfoController.h"


@interface KRCommentBtn : UIButton
// 右上角tip
@property (nonatomic, copy) NSString *tipText;
@end
@implementation KRCommentBtn

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleLabel.backgroundColor = [UIColor redColor];
        self.titleLabel.font = [UIFont systemFontOfSize:10];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

- (void)setTipText:(NSString *)tipText
{
    _tipText = tipText;
    
    [self setTitle:[NSString stringWithFormat:@"%@", tipText] forState:UIControlStateNormal];
//    [self setTitle:@"99" forState:UIControlStateNormal];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGSize fontSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font];
    CGFloat titleW = fontSize.width * 1.4;
    CGFloat titleH = fontSize.height * 1.2;
    self.titleLabel.width = titleW > 21 ? titleW : 21;
    self.titleLabel.height = titleH;
    
    self.titleLabel.x = self.width - self.titleLabel.width * 0.8;
    self.titleLabel.y = -self.titleLabel.height * 0.1;
    
    self.titleLabel.layer.cornerRadius = self.titleLabel.frame.size.height * 0.5;
    self.titleLabel.clipsToBounds = YES;

}

@end

@interface KRReadPostController () <KRWebViewCellDelegate>
@property (nonatomic, strong) KRReadPost *readPost;
@property (nonatomic, assign) NSUInteger offset;
@property (nonatomic, weak) KRCommentBtn *commentBtn;

/** webView高度 */
@property (nonatomic, assign) CGFloat webviewCellHeight;

/** webView加载进度条 */
@property (nonatomic, weak) NJKWebViewProgressView *progressView;

/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDataTask;
@property (nonatomic, assign, getter=isError) BOOL error;
@end

@implementation KRReadPostController

- (instancetype)init
{
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerClass:[KRCommentCell class] forCellReuseIdentifier:@"comment"];
    
    self.tableView.backgroundColor = [UIColor whiteColor];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    /* 加载数据 */
    [self loadData];

    
    // 监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setWebviewHeight:) name:KRWebviewDidGetHeightNotification object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    KRLog(@"%@, %f", self.readPost.title, self.webviewCellHeight);
    if (!self.readPost) {
        // 显示指示器
        [SVProgressHUD show];
        self.tableView.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
    }
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

/**
 *  加载数据
 */
- (void)loadData
{
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRTopicView;
        requestParams[@"id"] = self.topicID;
        requestParams[@"limit"] = @"10";
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];

    } success:^(NSURLSessionDataTask *task, id json) {
        if (task != self.currentDataTask) return;

        self.error = NO;
        self.tableView.scrollEnabled = YES;

        // 上拉刷新控件
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        

        self.readPost = [KRReadPost mj_objectWithKeyValues:json[@"result"]];
        
        self.offset += 10;
        if (self.offset > [self.readPost.commentcount integerValue]) {
            self.offset = [self.readPost.commentcount integerValue];
        }
        
        /* 设置导航栏右边按钮 */
        // 收藏
        UIBarButtonItem *favoritesBtn = [UIBarButtonItem itemWithTarget:self action:@selector(favBtnClick) image:@"ico_topfavorites" selectImage:@"ico_topfavorites_over"];
        // 评论
        KRCommentBtn *commentButton = [[KRCommentBtn alloc] init];
        UIBarButtonItem *commentBtn = [UIBarButtonItem itemWithCustomBtn:commentButton Target:self action:@selector(commentBtnClick) image:@"ico_topcomment"];
        [(KRCommentBtn *)commentBtn.barButton setTipText:self.readPost.commentCount];
        // 分享
        UIBarButtonItem *shareBtn = [UIBarButtonItem itemWithTarget:self action:@selector(shareBtnClick) image:@"ico_topshare"];
        
        self.navigationItem.rightBarButtonItems = @[shareBtn, commentBtn, favoritesBtn];
        
        [self.tableView reloadData];
        
        // 移除蒙板
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (task != self.currentDataTask) return;
        self.error = YES;
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙"];
        });
        KRLog(@"%@, %@", self, error);
    }];
}

- (void)favBtnClick
{
    KRLog(@"%s", __func__);
}

- (void)commentBtnClick
{
    KRLog(@"%s", __func__);
}

- (void)shareBtnClick
{
    KRLog(@"%s", __func__);
}

/**
 *  加载更多评论
 */
- (void)loadMoreData
{
    KRLog(@"从第%d条评论开始加载", (int)self.offset);
    
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRTopicView;
        requestParams[@"id"] = self.topicID;
        requestParams[@"limit"] = @"10";
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;

        KRReadPost *readPost = [KRReadPost mj_objectWithKeyValues:json[@"result"]];
        NSArray *readComment = readPost.commentList;
        [self.readPost.commentList addObjectsFromArray:readComment];
        
        // 重新设置顶部评论数
        self.commentBtn.tipText = readPost.commentcount;
        [self.tableView reloadData];
        
        self.offset += 10;
        if (self.offset > [readPost.commentcount integerValue]) {
            self.offset = [readPost.commentcount integerValue];
            if (readComment.count == 0) {
                [SVProgressHUD showInfoWithStatus:@"已无更多评论"];
            }
            
        }
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;

        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        [SVProgressHUD showErrorWithStatus:@"网络繁忙！"];

        KRLog(@"%@, %@", self, error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isError) return 1; // 请求失败
    if (!self.readPost) return 0;
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isError) return 1; // 请求失败
    return section < 3 ? 1 : self.readPost.commentList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"请求超时"];
        return cell;
    }
    
    if (indexPath.section == 0) {
        KRReadTitleCell *cell = [KRReadTitleCell cellWithTableView:tableView];
        cell.title = self.readPost.title;
        cell.cateName = self.readPost.cateName;
        return cell;
    } else if (indexPath.section == 1) {
        KRPostInfoCell *cell = [KRPostInfoCell cellWithTableView:tableView];
        cell.avatar = self.readPost.avatar;
        cell.userName = self.readPost.userName;
        cell.createTime = self.readPost.createTime;
        cell.viewCount = self.readPost.viewCount;
        return cell;
    } else if (indexPath.section == 2) {
        KRWebViewCell *cell = [KRWebViewCell cellWithTableView:tableView];
        cell.delegate = self;
        cell.url = self.readPost.url;
        return cell;
    } else if (indexPath.section == 3) {
        KRCommentCell *cell = [KRCommentCell cellWithTableView:tableView];
        KRReadComment *readComment = self.readPost.commentList[indexPath.row];
        cell.readComment = readComment;
        return cell;
    }
    return nil;
}

#pragma mark - KRWebViewCellDelegate
/**
 *  webView的加载进度
 */
- (void)webViewCellWithProgress:(float)progress
{
    if (progress == 0) KRLog(@"---正在加载webview---");
    KRLog(@"当前webView进度 : %f", progress);
    if (progress == 1.0) KRLog(@"---webview加载完成---");
    
    [self.progressView setProgress:progress animated:YES];
}

- (NJKWebViewProgressView *)progressView
{
    if (!_progressView) {

        CGFloat progressBarHeight = 2.f;
        CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
        CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
        NJKWebViewProgressView *progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
        progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        [progressView.progressBarView setBackgroundColor:KRColor(111, 143, 18)];
        [self.navigationController.navigationBar addSubview:progressView];
        self.progressView = progressView;
    }
    return _progressView;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.currentDataTask cancel];
    self.currentDataTask = nil;
    [SVProgressHUD dismiss];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    // Remove progress view
    // because UINavigationBar is shared with other ViewControllers
    [_progressView removeFromSuperview];
}

/*
 * 点击了图片或链接
 */
- (void)webViewCellWithUrl:(NSString *)url ID:(NSString *)ID
{
    if ([url containsPartString:@"info"]) {
        /* haodourecipe://haodou.com/recipe/info/?id=210823  单条食谱 */
        
        KRRecipeInfoController *infoVc = [[KRRecipeInfoController alloc] init];
        infoVc.recipeID = ID; // RecipeId
        [self.navigationController pushViewController:infoVc animated:YES];
        
    } else if ([url containsPartString:@"topic"]) {
        /* haodourecipe://haodou.com/opentopic/?url=http%3A%2F%2Fgroup.haodou.com%2Ftopic-328039.html&id=328039 单条阅读 */
        
        KRReadPostController *readPostVc = [[KRReadPostController alloc] init];
        readPostVc.topicID = ID;
        [self.navigationController pushViewController:readPostVc animated:YES];
        
    } else {
        /*  haodourecipe://haodou.com/user/wo/?id=642281 用户 */
        
    }

}


#pragma mark - UITableViewDelegate

//CGFloat _webviewHeight;

- (void)setWebviewHeight:(NSNotification *)notification
{
    KRLog(@"webView真实高度 : %f", [notification.userInfo[KRWebviewHeight] floatValue]);
    self.webviewCellHeight = [notification.userInfo[KRWebviewHeight] floatValue];
    self.webviewCellHeight -= KRWebViewOffset;
    [self.tableView reloadData];
    
#warning(NJKWebViewProgressView) 移除进度条
    [self webViewCellWithProgress:1.0];
}

/**
 *  返回cell的高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;

    if (indexPath.section == 0) {
        return 110;
    } else if (indexPath.section == 1){
        return 70;
    } else if (indexPath.section == 2) {  // webview
#warning cellHeigth
        return self.webviewCellHeight;
    } else if (indexPath.section == 3){
        return [tableView fd_heightForCellWithIdentifier:@"comment" cacheByIndexPath:indexPath configuration:^(KRCommentCell *cell) {
            KRReadComment *readComment = self.readPost.commentList[indexPath.row];
            cell.readComment = readComment;
        }];
    } else {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
        [self loadData];
        [SVProgressHUD show];
        return;
    }
}

/**
 *  每组头部标题
 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section != 3) return nil;
    
    UILabel *commentCountLable = [[UILabel alloc] init];
    commentCountLable.backgroundColor = [UIColor whiteColor];
    [commentCountLable setText:[NSString stringWithFormat:@"    评论(%@)", self.readPost.commentCount]];

    return commentCountLable;
}

/**
 *  每组头部的高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 3) return 50;
    
    return 0.001;
}

/**
 *  每组尾部的高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

@end